// 运行时配置
import {message} from 'antd';
import {history} from 'umi';
import {getLoginUserInfo} from '@/services/system/SysLogin';
import {HOST} from '@/constants';


export const request = {
  timeout: 5000,
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': '*',
    'adminToken': window.localStorage.getItem('token'),
  },

  errorConfig: {
    errorThrower() {
    },

    /* 错误接收及处理 */
    errorHandler: (error, opts) => {
      message.destroy();
      if (opts?.skipErrorHandler) throw error;
      if (error.response) {
        // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
        message.error(`响应错误，状态码：${error.response.status}`).then();
        // 未授权，跳转到登录
        if (error.response.status === 401) {
          window.location.href = '/login';
        }
      } else if (error.request) {
        // 请求已经成功发起，但没有收到响应
        message.error('没有响应，请重试！').then();
      } else {
        // 发送请求时出了点问题
        message.error('请求错误，请重试！').then();
      }
    },
  },

  /* 请求拦截器 */
  requestInterceptors: [
    (config) => {
      if (!config.baseURL) {
        config.baseURL = HOST;
      }
      return {...config};
    },
  ],

  /* 响应拦截器 */
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      const {data} = response;
      if (data.code === -1) {
        message.destroy();
        message.error(data.message).then();
      }
      return response;
    },
  ],
};


const arrToTree = (arr, parent = 0) =>
  arr.filter(item => item.pid === parent)
    .map(child => ({...child, routes: arrToTree(arr, child.id)}));

export async function getInitialState() {
  let initialState = {loginInfo: {}, routes: [], access: []};

  if (history.location.pathname !== '/login') {
    let resp = await getLoginUserInfo();
    if (0 === resp.code) {
      // 侧边栏菜单
      let routes = arrToTree(
        (resp.data?.menuList ?? [])
          .filter(d => d.menuType === 'M')
          .map(d => {
            d.name = d.menuName;
            d.hideInMenu = d.visible !== 1;
            return d;
          }),
      );

      // 完整侧边栏
      routes = [
        {path: '/', component: '@/pages/Index/App', icon: 'icon-shouye', name: '首页管理'},
        {path: '/login', component: '@/pages/Login/App', layout: false},
        ...routes,
        {path: '/*', component: '@/pages/404.js'},
      ];

      // 访问权限
      let access = (resp.data?.menuList ?? [])
        .filter(d => d.permission !== '' && d.permission !== null)
        .map(d => d.permission.replaceAll(':', '_'));

      let accessObj = {};
      access.forEach(d => {
        accessObj[d] = true;
      });

      initialState.loginInfo = resp.data;
      initialState.routes = routes;
      initialState.access = accessObj;
    }
  }

  return initialState;
}